//
//  MenuIconView.m
//  TwitterPlane
//
//  Created by kazuyuki takahashi on 10/02/11.
//  Copyright 2010 by invisibledesigner.com. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "MenuIconView.h"
#import "MenuView.h"
#import "TwitFormWindowController.h"
#import "PreferencesController.h"

//tags
static const NSInteger kTwitIconTag = 1;
static const NSInteger kPreferenceIconTag = 2;
static const NSInteger kHomeIconTag = 3;
static const NSInteger kMinimizeIconTag = 4;


@implementation MenuIconView

@dynamic backgroundAlpha;

- (CGFloat)backgroundAlpha
{
    return backgroundAlpha_;
}

- (void)setBackgroundAlpha:(CGFloat)bga
{
    backgroundAlpha_ = bga;
    [self setNeedsDisplay:YES];
}

- (id)animationForKey:(NSString *)key
{
    if ([key isEqualToString:@"backgroundAlpha"]) {
        CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:key];
        [anim setDuration:0.2];
        return anim;
    }
    return [super animationForKey:key];
}

- (void)updateTrackingAreas
{
    for (NSTrackingArea *ta in [[[self trackingAreas] copy] autorelease]) {
        [self removeTrackingArea:ta];
    }
    
    NSTrackingArea *ta = [[[NSTrackingArea alloc] initWithRect:[self bounds]
                                                       options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
                                                         owner:self
                                                      userInfo:nil] autorelease];
    [self addTrackingArea:ta];
}

- (void)mouseDown:(NSEvent*)event
{
    NSInteger tag = [self tag];
    
    if (tag == kTwitIconTag) {
        [[TwitFormWindowController sharedController] showWindow:self];
    } else if (tag == kPreferenceIconTag) {
        [[PreferencesController sharedController] showWindow:self];
    } else if (tag == kHomeIconTag) {
        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://twitter.com/"]];
    } else if (tag == kMinimizeIconTag) {
        [[self animator] setBackgroundAlpha:0];
        [[self window] miniaturize:self];
    } else {
        NSAssert(NO, @"invalid tag");
    }
    
    //メニューをフェードアウト
    [(MenuView*)[self superview] fadeout];
}

- (void)mouseEntered:(NSEvent *)theEvent
{
    [[self animator] setBackgroundAlpha:0.8];
}

- (void)mouseExited:(NSEvent *)theEvent
{
    [[self animator] setBackgroundAlpha:0];
}

- (void)drawRect:(NSRect)dirtyRect
{
    CGFloat bga = [self backgroundAlpha];
    if (bga > 0) {
        [[NSColor colorWithDeviceWhite:1 alpha:bga] set];
        NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:[self bounds] xRadius:6 yRadius:6];
        [path fill];
    }
    
    [super drawRect:dirtyRect];
}

@end
